package com.geotmt.billingcenter.common.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Descriptinon: 类描述
 * @Author:       yanghanwei
 * @Mail:         yanghanwei@geotmt.com
 * @CreateDate:   2018/12/3 17:06
 * @Version:      v3
 */
@SuppressWarnings("all")
public class RestTemplateUtil {

    private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);

	public static RestTemplate getRestTemplate() {
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new ByteArrayHttpMessageConverter());
        /** 解决乱码的converter */
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        messageConverters.add(stringHttpMessageConverter);
        messageConverters.add(new ResourceHttpMessageConverter());
        messageConverters.add(new SourceHttpMessageConverter());
        messageConverters.add(new AllEncompassingFormHttpMessageConverter());
        
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setMessageConverters(messageConverters);
        
        return restTemplate;
	}


    /**
     * 封装 restTemplate 方法
     * @param headerName
     * @param method
     * @param url
     * @param params
     * @return
     */
	public static String getResult(MediaType headerName, HttpMethod method, String url, Map<String,Object> params) {
        try{
            logger.info("active method is RestTemplateUtil => getRestTemplate");

            StringBuffer urlBuff = new StringBuffer(url);
            List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
            messageConverters.add(new ByteArrayHttpMessageConverter());
            /** 解决乱码的converter */
            StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
            messageConverters.add(stringHttpMessageConverter);
            messageConverters.add(new ResourceHttpMessageConverter());
            messageConverters.add(new SourceHttpMessageConverter());
            messageConverters.add(new AllEncompassingFormHttpMessageConverter());

            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            //60s
            requestFactory.setConnectTimeout(10*1000);
            requestFactory.setReadTimeout(20*1000);

            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.setMessageConverters(messageConverters);

            //请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(headerName);

            HttpEntity<String> entity = null;
            HttpEntity entityForm = null;
            if(HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method)){
                headers.add("Accept", headerName.toString());
                if(MediaType.APPLICATION_JSON.equals(headerName)){
                    entity = new HttpEntity<String>(JSON.toJSONString(params),headers);
                }
                if(MediaType.APPLICATION_FORM_URLENCODED.equals(headerName)){
                    LinkedMultiValueMap body=new LinkedMultiValueMap();
                    for(Map.Entry<String,Object> entry : params.entrySet()){
                        body.add(entry.getKey(),entry.getValue());
                        entityForm = new HttpEntity(body, headers);
                    }
                }
            }
            if(HttpMethod.DELETE.equals(method) || HttpMethod.GET.equals(method)){
                entity = new HttpEntity<String>(headers);
                if(params != null && params.size()>0){
                    urlBuff.append("?");
                    for (Map.Entry<String, Object> entry : params.entrySet()) {
                        StringBuffer subUrl = new StringBuffer();
                        subUrl.append(entry.getKey())
                                .append("=")
                                .append(entry.getValue())
                                .append("&");
                        urlBuff.append(subUrl);
                    }
                    url = urlBuff.substring(0,urlBuff.length()-1);
                }
            }
            if(MediaType.APPLICATION_JSON.equals(headerName)){
                return restTemplate.exchange(url, method, entity, String.class).getBody();
            }else{
                return restTemplate.exchange(url, method, entityForm, String.class).getBody();
            }
        }catch (Exception e){
            logger.info(" RestTemplateUtil => getRestTemplate is exception :"+e);
            return null;
        }
	}

}
